package cn.jdx.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
//层层关联,最终是为了拿到安全管理器(基本上就是死代码,都是一样的编写方式)
public class ShiroConfig {

    @Bean(name = "userRealm")
    //(1)创建realm类
    public UserRealm userRealm() {
        return new UserRealm();
    }

    @Bean(name = "securityManager")
    //(2)DefaultWebSecurityManager
    public DefaultWebSecurityManager getDefaultWebSecurity(@Qualifier("userRealm") UserRealm userRealm) {
        //1.创建对象
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //2.关联用户认证对象(UserRealm)
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean
    //(3)获取ShiroFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //1.设置安全管理器
        bean.setSecurityManager(securityManager);
        //2.添加Shiro的内置过滤
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");
        filterMap.put("/user/*", "authc");
        bean.setFilterChainDefinitionMap(filterMap);
        //3.设置登录的请求
        bean.setLoginUrl("/toLogin");
        //4.指定未授权跳转链接
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }
}
